package com.industrial.premu.service.impl.sqsj;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.DgQuantityQualityManage;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportGuotu;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportShuili;
import com.industrial.premu.mapper.DgQuantityQualityManageMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportShuiliMapper;
import com.industrial.premu.service.IPreMuImportShuiliService;
import com.industrial.premu.util.ValidationUtil;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * 规上企业导入数据-水利局数据Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-25
 */
@Service
public class PreMuImportShuiliServiceImpl implements IPreMuImportShuiliService
{
    @Autowired
    private PreMuImportShuiliMapper preMuImportShuiliMapper;

    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;

    @Autowired
    private DgQuantityQualityManageMapper dgQuantityQualityManageMapper;

    private static final int BATCH_SIZE = 300;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;

    /**
     * 查询规上企业导入数据-水利局数据
     *
     * @param id 规上企业导入数据-水利局数据主键
     * @return 规上企业导入数据-水利局数据
     */
    @Override
    public PreMuImportShuili selectPreMuImportShuiliById(String id)
    {
        return preMuImportShuiliMapper.selectPreMuImportShuiliById(id);
    }

    /**
     * 查询规上企业导入数据-水利局数据列表
     *
     * @param preMuImportShuili 规上企业导入数据-水利局数据
     * @return 规上企业导入数据-水利局数据
     */
    @Override
    public List<PreMuImportShuili> selectPreMuImportShuiliList(PreMuImportShuili preMuImportShuili)
    {
        return preMuImportShuiliMapper.selectPreMuImportShuiliList(preMuImportShuili);
    }

    /**
     * 新增规上企业导入数据-水利局数据
     *
     * @param preMuImportShuili 规上企业导入数据-水利局数据
     * @return 结果
     */
    @Override
    public int insertPreMuImportShuili(PreMuImportShuili preMuImportShuili)
    {
        return preMuImportShuiliMapper.insertPreMuImportShuili(preMuImportShuili);
    }

    /**
     * 修改规上企业导入数据-水利局数据
     *
     * @param preMuImportShuili 规上企业导入数据-水利局数据
     * @return 结果
     */
    @Override
    public int updatePreMuImportShuili(PreMuImportShuili preMuImportShuili)
    {
        return preMuImportShuiliMapper.updatePreMuImportShuili(preMuImportShuili);
    }

    /**
     * 批量删除规上企业导入数据-水利局数据
     *
     * @param ids 需要删除的规上企业导入数据-水利局数据主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportShuiliByIds(String[] ids)
    {
        return preMuImportShuiliMapper.deletePreMuImportShuiliByIds(ids);
    }

    /**
     * 删除规上企业导入数据-水利局数据信息
     *
     * @param id 规上企业导入数据-水利局数据主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportShuiliById(String id)
    {
        return preMuImportShuiliMapper.deletePreMuImportShuiliById(id);
    }

    @Override
    public void removeData(PreMuImportShuili params,String deptCode) {
        preMuImportShuiliMapper.removeData(params);

        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(params.getYear());
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
    }

    @Override
    public AjaxResult importShuiliExcelData(String year, String companyType, MultipartFile file) {
        try{
            ExcelUtil<PreMuImportShuili> util = new ExcelUtil<PreMuImportShuili>(PreMuImportShuili.class);
            List<PreMuImportShuili> preMuImportShuilis = util.importExcel(file.getInputStream());
            if (StringUtils.isNull(preMuImportShuilis) || preMuImportShuilis.size() == 0) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","导入数据不能为空");
                return AjaxResult.error("导入失败",resultMap);
            }

            List<PreMuImportShuili> realList = new ArrayList<PreMuImportShuili>();
            int successNum = 0;
            int updateNum = 0;
            int failureNum = 0;

            //企业名称为空的错误数据量
            int companyNameBlankCount = 0;
            //值为空的错误量
            int valueErrorCount = 0;
            int valueZeroCount = 0;
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            StringBuilder allMsg = new StringBuilder();

            //批处理用
            List<String> usccList = new ArrayList<String>();
            List<String> mcImportExistList = new ArrayList<String>();
            List<PreMuImportShuili> addImportList = new ArrayList<PreMuImportShuili>();
            List<PreMuImportShuili> updateImportList = new ArrayList<PreMuImportShuili>();

            if (preMuImportShuilis != null && !preMuImportShuilis.isEmpty()) {

                preMuImportShuilis.forEach(data -> {
                    if (data.getUscc() != null && !"".equals(data.getUscc())){
                        usccList.add(data.getUscc().trim());
                        realList.add(data);
                    }
                });
            }

            HashSet<String> distinctSet = new HashSet<>();
            for (String uscc : usccList){
                if (!distinctSet.add(uscc)){
                    Map<String,String> resultMap = new HashMap<>();
                    resultMap.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                    return AjaxResult.error("导入失败",resultMap);
                };
            }

            mcImportExistList = preMuImportShuiliMapper.getImportShuiLiExistList(year, usccList);
            ValidationUtil.validate(realList);

            int travel = 1;
            for (int i = 0; i < preMuImportShuilis.size(); i++) {
                travel++;
                PreMuImportShuili preMuImportShuili = preMuImportShuilis.get(i);
                preMuImportShuili.setYear(year);
                String uscc = preMuImportShuili.getUscc();
                if (uscc == null || "".equals(uscc) || year == null || "".equals(year)) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + preMuImportShuili.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "社会信用代码或年份不能为空");
                    continue;
                } else {
                    uscc = uscc.trim();
                    preMuImportShuili.setUscc(uscc);
                }

                if(StringUtils.isBlank(preMuImportShuili.getCompanyName())){
                    companyNameBlankCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + preMuImportShuili.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "企业名称不能为空");
                    continue;
                }


                if(preMuImportShuili.getWaterBureau() == null){
                    valueErrorCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + preMuImportShuili.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "耗水量不能为空");
                    continue;
                }

                if(preMuImportShuili.getWaterBureau().compareTo(BigDecimal.ZERO) < 1){
                    valueZeroCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + preMuImportShuili.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "耗水量不能小于等于0");
                    continue;
                }

                if (mcImportExistList.contains(uscc)) {
                    preMuImportShuili.setDelFlag("0");
                    updateImportList.add(preMuImportShuili);
                } else {
                    preMuImportShuili.setId(UUID.randomUUID().toString().replace("-", ""));
                    preMuImportShuili.setDelFlag("0");
                    preMuImportShuili.setCreateDate(DateUtils.getNowDate());
                    preMuImportShuili.setCreateBy(SecurityUtils.getUserId());
                    addImportList.add(preMuImportShuili);
                }

                if (addImportList != null && addImportList.size() >= BATCH_SIZE) {

                    int importNum = preMuImportShuiliMapper.batchSave(addImportList);
                    successNum += importNum;
                    addImportList.clear();
                }
                if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportShuiliMapper.batchUpdateByUscc(year, updateImportList);
                    successNum += importNum;
                    updateNum += importNum;
                    updateImportList.clear();
                }
            }
            if (addImportList != null && !addImportList.isEmpty()) {

                int importNum = preMuImportShuiliMapper.batchSave(addImportList);
                successNum += importNum;
                addImportList.clear();
            }
            if (updateImportList != null && !updateImportList.isEmpty()) {
                int importNum = preMuImportShuiliMapper.batchUpdateByUscc(year, updateImportList);
                successNum += importNum;
                updateNum += importNum;
                updateImportList.clear();
            }

            if (failureNum > 0) {
                allMsg.insert(0, "<br/>很抱歉，错误如下：" + failureMsg.toString());
            }
            if (successNum > 0) {
                allMsg.insert(0, "恭喜您，共" + successNum + " 条数据导入成功！");
            }


            //企业名称为空的数量
            if(companyNameBlankCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("企业名称不能为空");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(companyNameBlankCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("企业名称不能为空");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }
            //值小于0
            if(valueZeroCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值小于0的错误");

                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(valueZeroCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值小于0的错误");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }


            //值存在错误的情况
            if(valueErrorCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值不存在或者是格式有误");

                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(valueErrorCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("水利局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值不存在或者是格式有误");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }

            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg","恭喜您，共" + successNum + " 条数据导入成功！");
            resultMap.put("sum",String.valueOf(successNum));
            resultMap.put("updateNum",String.valueOf(updateNum));
            resultMap.put("failureNum",String.valueOf(failureNum));
            resultMap.put("allMsg",allMsg.toString());
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            String requestURI = "/industrial-premu/importExcelData";
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            return AjaxResult.warn("导入失败");
        }
    }
}
